# coding=utf-8

from flask import render_template, request, g, redirect, url_for
from over.handlers.my import mod
from over.handlers.router import Router
from over.model import TradeRecord, Recharge, db
from over.handlers.helper import new_order_number, new_pay_number, jsonify

router = Router()


@router('/recharge')
class RechargeRouter(object):
    __router_name__ = 'recharge'

    @router('/', methods=['GET', 'POST'])
    def index(self):
        recharges = Recharge.latest_recharges(g.user.id)
        if request.method == 'POST':
            pay_method = request.form.get('pay_method')
            if pay_method != 0:
                pass

            amount = request.form.get('amount', type=float)
            amount *= 100
            order_num = new_order_number()
            print(amount, order_num, pay_method)
            recharge = Recharge(amount=amount, pay_method=pay_method, user_id=g.user.id, order_num=order_num)
            db.session.add(recharge)
            db.session.commit()

            # TODO: 转到支付宝对应的接口
            return redirect(url_for('over.handlers.my.recharge.index'))

        return render_template('my/recharge/index.html', recharges=recharges)

    @router('/pay', methods=['POST'])
    def pay(self):
        order_num = request.form.get('orderNum')
        recharge = Recharge.get_by_order_num(order_num, g.user.id)
        pay_num = new_pay_number()
        recharge.pay_num = pay_num
        db.session.add(recharge)
        db.session.commit()

        return jsonify({'success':True, 'payNum': pay_num, 'amount': recharge.amount})


    @router('/cancel', methods=['POST'])
    def cancel(self):
        order_num = request.form.get('orderNum')
        recharge = Recharge.get_by_order_num(order_num, g.user.id)
        recharge.status = Recharge.PAY_CANCEL
        db.session.add(recharge)
        db.session.commit()

        return redirect(url_for('over.handlers.my.recharge.index'))


router.register_url_rules(mod)
